/**
 * 裁剪框工具类
 * 包含所有与裁剪框相关的计算和操作函数
 */

export interface CropRect {
  x: number;
  y: number;
  width: number;
  height: number;
  matrix?: {
    x: number;
    y: number;
    scale: number;
    rotate: number;
  };
}

export interface DragHandle {
  x: number;
  y: number;
  type:
    | "top-left"
    | "top-right"
    | "bottom-left"
    | "bottom-right"
    | "top"
    | "bottom"
    | "left"
    | "right";
}

export interface ImagePosition {
  x: number;
  y: number;
}

export interface ImageSize {
  width: number;
  height: number;
}

/**
 * 根据toolKey设置裁剪框
 * @param toolKey - 工具类型键值
 * @param imageSize - 图片显示尺寸
 * @param containerSize - 容器尺寸
 * @param marginHorizontal - 水平边距
 * @param rotation - 旋转角度（用于处理旋转后的宽高交换）
 * @returns 裁剪框位置和尺寸
 */
export const updateCropRectByToolKey = (
  toolKey?: string,
  imageSize?: ImageSize,
  containerSize?: { width: number; height: number }
): CropRect => {
  if (
    !imageSize ||
    !containerSize ||
    imageSize.width <= 0 ||
    imageSize.height <= 0 ||
    containerSize.width <= 0 ||
    containerSize.height <= 0
  ) {
    return { x: 0, y: 0, width: 0, height: 0 };
  }

  // 考虑旋转后的实际宽高
  const actualWidth = imageSize.width;
  const actualHeight = imageSize.height;

  // 相对于图片实际显示位置的坐标（从0,0开始）
  const imageX = 0;
  const imageY = 0;

  switch (toolKey) {
    case "crop":
    case undefined:
    case "":
      // crop模式或默认情况下，裁剪框与图片大小一致
      return {
        x: imageX,
        y: imageY,
        width: actualWidth,
        height: actualHeight,
      };

    case "original":
      // original模式下，裁剪框与图片大小一致，但不显示拖动点
      return {
        x: imageX,
        y: imageY,
        width: actualWidth,
        height: actualHeight,
      };

    case "1_1":
    case "4_3":
    case "3_4":
    case "2_3":
    case "3_2":
    case "9_16":
    case "16_9":
      // 比例模式下，根据图片宽度和比例计算裁剪框
      const ratio = toolKey.split("_").map(Number);
      const targetRatio = ratio[1] / ratio[0];

      let cropWidth = actualWidth;
      let cropHeight = cropWidth * targetRatio;

      // 如果高度超出图片，按高度缩放
      if (cropHeight > actualHeight) {
        cropHeight = actualHeight;
        cropWidth = cropHeight / targetRatio;
      }

      // 确保裁剪框在图片范围内居中
      const centerX = imageX + actualWidth / 2;
      const centerY = imageY + actualHeight / 2;

      // 使用Math.round避免浮点数精度问题
      return {
        x: Math.round(centerX - cropWidth / 2),
        y: Math.round(centerY - cropHeight / 2),
        width: Math.round(cropWidth),
        height: Math.round(cropHeight),
      };

    case "circle":
      // 圆形模式下，生成正方形裁剪框
      const circleSize = Math.min(actualWidth, actualHeight);
      const circleCenterX = imageX + actualWidth / 2;
      const circleCenterY = imageY + actualHeight / 2;

      // 使用Math.round避免浮点数精度问题
      return {
        x: Math.round(circleCenterX - circleSize / 2),
        y: Math.round(circleCenterY - circleSize / 2),
        width: Math.round(circleSize),
        height: Math.round(circleSize),
      };

    default:
      // 默认不显示裁剪框
      return { x: 0, y: 0, width: 0, height: 0 };
  }
};

/**
 * 获取拖动点的位置
 * @param cropRect - 当前裁剪框
 * @param toolKey - 工具类型键值
 * @returns 拖动点数组
 */
export const getDragHandles = (
  cropRect: CropRect,
  toolKey?: string
): DragHandle[] => {
  "worklet";
  const handles: DragHandle[] = [];
  const { x, y, width, height } = cropRect;

  // 确保裁剪框有有效尺寸
  if (
    width <= 0 ||
    height <= 0 ||
    !isFinite(x) ||
    !isFinite(y) ||
    !isFinite(width) ||
    !isFinite(height)
  ) {
    return handles;
  }

  // 使用四舍五入减少抖动
  const roundedX = Math.round(x * 100) / 100;
  const roundedY = Math.round(y * 100) / 100;
  const roundedWidth = Math.round(width * 100) / 100;
  const roundedHeight = Math.round(height * 100) / 100;

  // original模式下不显示拖动点
  if (toolKey === "original") {
    return handles;
  }

  // 比例模式下只显示四角拖动点
  const isRatioMode = [
    "1_1",
    "4_3",
    "3_4",
    "2_3",
    "3_2",
    "9_16",
    "16_9",
  ].includes(toolKey || "");

  if (isRatioMode || toolKey === "crop") {
    // 四个角 - 位于裁剪框的拐角处
    handles.push({ x: roundedX, y: roundedY, type: "top-left" });
    handles.push({ x: roundedX + roundedWidth, y: roundedY, type: "top-right" });
    handles.push({ x: roundedX, y: roundedY + roundedHeight, type: "bottom-left" });
    handles.push({ x: roundedX + roundedWidth, y: roundedY + roundedHeight, type: "bottom-right" });
  }

  // 只有crop模式下显示四条边的中点
  if (toolKey === "crop") {
    handles.push({ x: roundedX + roundedWidth / 2, y: roundedY, type: "top" });
    handles.push({ x: roundedX + roundedWidth / 2, y: roundedY + roundedHeight, type: "bottom" });
    handles.push({ x: roundedX, y: roundedY + roundedHeight / 2, type: "left" });
    handles.push({ x: roundedX + roundedWidth, y: roundedY + roundedHeight / 2, type: "right" });
  }

  return handles;
};

/**
 * 生成矩形裁剪框路径
 * @param cropRect - 裁剪框位置和尺寸
 * @returns SVG路径字符串
 */
export const getCropRectPath = (cropRect: CropRect): string => {
  "worklet";
  const { x, y, width, height } = cropRect;
  if (
    width <= 0 ||
    height <= 0 ||
    !isFinite(x) ||
    !isFinite(y) ||
    !isFinite(width) ||
    !isFinite(height)
  ) {
    return "";
  }
  
  // 使用四舍五入减少抖动
  const roundedX = Math.round(x * 100) / 100;
  const roundedY = Math.round(y * 100) / 100;
  const roundedWidth = Math.round(width * 100) / 100;
  const roundedHeight = Math.round(height * 100) / 100;
  
  return `M ${roundedX} ${roundedY} L ${roundedX + roundedWidth} ${roundedY} L ${roundedX + roundedWidth} ${roundedY + roundedHeight} L ${roundedX} ${
    roundedY + roundedHeight
  } Z`;
};

/**
 * 生成圆形裁剪框路径
 * @param cropRect - 裁剪框位置和尺寸
 * @returns SVG路径字符串
 */
export const getCircleCropPath = (cropRect: CropRect): string => {
  "worklet";
  const { x, y, width, height } = cropRect;
  if (
    width <= 0 ||
    height <= 0 ||
    !isFinite(x) ||
    !isFinite(y) ||
    !isFinite(width) ||
    !isFinite(height)
  ) {
    return "";
  }

  // 使用四舍五入减少抖动
  const roundedX = Math.round(x * 100) / 100;
  const roundedY = Math.round(y * 100) / 100;
  const roundedWidth = Math.round(width * 100) / 100;
  const roundedHeight = Math.round(height * 100) / 100;

  const centerX = roundedX + roundedWidth / 2;
  const centerY = roundedY + roundedHeight / 2;
  const radius = Math.min(roundedWidth, roundedHeight) / 2;

  const roundedCenterX = Math.round(centerX * 100) / 100;
  const roundedCenterY = Math.round(centerY * 100) / 100;
  const roundedRadius = Math.round(radius * 100) / 100;

  return `M ${roundedCenterX} ${roundedCenterY - roundedRadius} A ${roundedRadius} ${roundedRadius} 0 1 0 ${
    roundedCenterX + 0.01
  } ${roundedCenterY - roundedRadius} Z`;
};

/**
 * 生成圆形裁剪路径
 * @param cropRect - 裁剪框位置和尺寸
 * @returns SVG路径字符串
 */
export const getCirclePath = (cropRect: CropRect): string => {
  const { x, y, width, height } = cropRect;
  if (
    width <= 0 ||
    height <= 0 ||
    !isFinite(x) ||
    !isFinite(y) ||
    !isFinite(width) ||
    !isFinite(height)
  ) {
    return "";
  }

  // 计算圆心和半径
  const centerX = x + width / 2;
  const centerY = y + height / 2;
  const radius = Math.min(width, height) / 2;

  return `M ${centerX} ${centerY - radius} A ${radius} ${radius} 0 1 0 ${
    centerX + 0.01
  } ${centerY - radius} Z`;
};

/**
 * 根据toolKey获取对应的裁剪路径
 * @param cropRect - 裁剪框位置和尺寸
 * @param toolKey - 工具类型键值
 * @returns SVG路径字符串
 */
export const getClipPathByToolKey = (
  cropRect: CropRect,
  toolKey?: string
): string => {
  // 圆形模式使用圆形路径
  if (toolKey === "circle") {
    return getCirclePath(cropRect);
  }

  // 其他模式使用矩形路径
  return getCropRectPath(cropRect);
};

/**
 * 生成拖动点路径
 * @param handle - 拖动点信息
 * @returns SVG路径字符串
 */
export const getHandlePath = (handle: DragHandle): string => {
  "worklet";
  const cornerSize = 12; // 减小拐角大小以适应小裁剪框
  const cornerHeight = 3; // 减小拐角厚度
  const edgeWidth = 20; // 减小边缘宽度
  const edgeHeight = 3; // 减小边缘厚度
  const radius = 1; // 小圆角

  switch (handle.type) {
    // 四个拐角 - 更小的L形拐角
    case "top-left":
      return `M ${handle.x} ${handle.y + radius} Q ${handle.x} ${handle.y} ${
        handle.x + radius
      } ${handle.y} L ${handle.x + cornerSize - radius} ${handle.y} Q ${
        handle.x + cornerSize
      } ${handle.y} ${handle.x + cornerSize} ${handle.y + radius} L ${
        handle.x + cornerSize
      } ${handle.y + cornerHeight} L ${handle.x + cornerHeight} ${
        handle.y + cornerHeight
      } L ${handle.x + cornerHeight} ${handle.y + cornerSize} L ${handle.x} ${
        handle.y + cornerSize
      } Z`;

    case "top-right":
      return `M ${handle.x} ${handle.y + radius} Q ${handle.x} ${handle.y} ${
        handle.x - radius
      } ${handle.y} L ${handle.x - cornerSize + radius} ${handle.y} Q ${
        handle.x - cornerSize
      } ${handle.y} ${handle.x - cornerSize} ${handle.y + radius} L ${
        handle.x - cornerSize
      } ${handle.y + cornerHeight} L ${handle.x - cornerHeight} ${
        handle.y + cornerHeight
      } L ${handle.x - cornerHeight} ${handle.y + cornerSize} L ${handle.x} ${
        handle.y + cornerSize
      } Z`;

    case "bottom-left":
      return `M ${handle.x} ${handle.y - radius} Q ${handle.x} ${handle.y} ${
        handle.x + radius
      } ${handle.y} L ${handle.x + cornerSize - radius} ${handle.y} Q ${
        handle.x + cornerSize
      } ${handle.y} ${handle.x + cornerSize} ${handle.y - radius} L ${
        handle.x + cornerSize
      } ${handle.y - cornerHeight} L ${handle.x + cornerHeight} ${
        handle.y - cornerHeight
      } L ${handle.x + cornerHeight} ${handle.y - cornerSize} L ${handle.x} ${
        handle.y - cornerSize
      } Z`;

    case "bottom-right":
      return `M ${handle.x} ${handle.y - radius} Q ${handle.x} ${handle.y} ${
        handle.x - radius
      } ${handle.y} L ${handle.x - cornerSize + radius} ${handle.y} Q ${
        handle.x - cornerSize
      } ${handle.y} ${handle.x - cornerSize} ${handle.y - radius} L ${
        handle.x - cornerSize
      } ${handle.y - cornerHeight} L ${handle.x - cornerHeight} ${
        handle.y - cornerHeight
      } L ${handle.x - cornerHeight} ${handle.y - cornerSize} L ${handle.x} ${
        handle.y - cornerSize
      } Z`;

    // 上下边缘 - 圆角横向长方形
    case "top":
      return `M ${handle.x - edgeWidth / 2 + radius} ${handle.y} Q ${
        handle.x - edgeWidth / 2
      } ${handle.y} ${handle.x - edgeWidth / 2} ${handle.y + radius} L ${
        handle.x - edgeWidth / 2
      } ${handle.y + edgeHeight - radius} Q ${handle.x - edgeWidth / 2} ${
        handle.y + edgeHeight
      } ${handle.x - edgeWidth / 2 + radius} ${handle.y + edgeHeight} L ${
        handle.x + edgeWidth / 2 - radius
      } ${handle.y + edgeHeight} Q ${handle.x + edgeWidth / 2} ${
        handle.y + edgeHeight
      } ${handle.x + edgeWidth / 2} ${handle.y + edgeHeight - radius} L ${
        handle.x + edgeWidth / 2
      } ${handle.y + radius} Q ${handle.x + edgeWidth / 2} ${handle.y} ${
        handle.x + edgeWidth / 2 - radius
      } ${handle.y} Z`;

    case "bottom":
      return `M ${handle.x - edgeWidth / 2 + radius} ${handle.y} Q ${
        handle.x - edgeWidth / 2
      } ${handle.y} ${handle.x - edgeWidth / 2} ${handle.y - radius} L ${
        handle.x - edgeWidth / 2
      } ${handle.y - edgeHeight + radius} Q ${handle.x - edgeWidth / 2} ${
        handle.y - edgeHeight
      } ${handle.x - edgeWidth / 2 + radius} ${handle.y - edgeHeight} L ${
        handle.x + edgeWidth / 2 - radius
      } ${handle.y - edgeHeight} Q ${handle.x + edgeWidth / 2} ${
        handle.y - edgeHeight
      } ${handle.x + edgeWidth / 2} ${handle.y - edgeHeight + radius} L ${
        handle.x + edgeWidth / 2
      } ${handle.y - radius} Q ${handle.x + edgeWidth / 2} ${handle.y} ${
        handle.x + edgeWidth / 2 - radius
      } ${handle.y} Z`;

    // 左右边缘 - 圆角竖向长方形
    case "left":
      return `M ${handle.x} ${handle.y - edgeWidth / 2 + radius} Q ${
        handle.x
      } ${handle.y - edgeWidth / 2} ${handle.x + radius} ${
        handle.y - edgeWidth / 2
      } L ${handle.x + edgeHeight - radius} ${handle.y - edgeWidth / 2} Q ${
        handle.x + edgeHeight
      } ${handle.y - edgeWidth / 2} ${handle.x + edgeHeight} ${
        handle.y - edgeWidth / 2 + radius
      } L ${handle.x + edgeHeight} ${handle.y + edgeWidth / 2 - radius} Q ${
        handle.x + edgeHeight
      } ${handle.y + edgeWidth / 2} ${handle.x + edgeHeight - radius} ${
        handle.y + edgeWidth / 2
      } L ${handle.x + radius} ${handle.y + edgeWidth / 2} Q ${handle.x} ${
        handle.y + edgeWidth / 2
      } ${handle.x} ${handle.y + edgeWidth / 2 - radius} Z`;

    case "right":
      return `M ${handle.x} ${handle.y - edgeWidth / 2 + radius} Q ${
        handle.x
      } ${handle.y - edgeWidth / 2} ${handle.x - radius} ${
        handle.y - edgeWidth / 2
      } L ${handle.x - edgeHeight + radius} ${handle.y - edgeWidth / 2} Q ${
        handle.x - edgeHeight
      } ${handle.y - edgeWidth / 2} ${handle.x - edgeHeight} ${
        handle.y - edgeWidth / 2 + radius
      } L ${handle.x - edgeHeight} ${handle.y + edgeWidth / 2 - radius} Q ${
        handle.x - edgeHeight
      } ${handle.y + edgeWidth / 2} ${handle.x - edgeHeight + radius} ${
        handle.y + edgeWidth / 2
      } L ${handle.x - radius} ${handle.y + edgeWidth / 2} Q ${handle.x} ${
        handle.y + edgeWidth / 2
      } ${handle.x} ${handle.y + edgeWidth / 2 - radius} Z`;

    default:
      return `M ${handle.x - 6} ${handle.y - 6} L ${handle.x + 6} ${
        handle.y - 6
      } L ${handle.x + 6} ${handle.y + 6} L ${handle.x - 6} ${handle.y + 6} Z`;
  }
};

/**
 * 生成网格路径
 * @param cropRect - 裁剪框位置和尺寸
 * @returns SVG路径字符串
 */
export const getGridPath = (cropRect: CropRect): string => {
  "worklet";
  if (cropRect.width <= 0 || cropRect.height <= 0) return "";

  const { x, y, width, height } = cropRect;
  if (!isFinite(x) || !isFinite(y) || !isFinite(width) || !isFinite(height)) {
    return "";
  }

  // 使用四舍五入减少抖动
  const roundedX = Math.round(x * 100) / 100;
  const roundedY = Math.round(y * 100) / 100;
  const roundedWidth = Math.round(width * 100) / 100;
  const roundedHeight = Math.round(height * 100) / 100;

  const gridSize = 3; // 3x3网格
  const cellWidth = roundedWidth / gridSize;
  const cellHeight = roundedHeight / gridSize;

  // 确保网格尺寸有效
  if (
    !isFinite(cellWidth) ||
    !isFinite(cellHeight) ||
    cellWidth <= 0 ||
    cellHeight <= 0
  ) {
    return "";
  }

  let path = "";

  // 垂直线
  for (let i = 1; i < gridSize; i++) {
    const lineX = roundedX + i * cellWidth;
    if (isFinite(lineX)) {
      path += `M ${Math.round(lineX * 100) / 100} ${roundedY} L ${Math.round(lineX * 100) / 100} ${roundedY + roundedHeight} `;
    }
  }

  // 水平线
  for (let i = 1; i < gridSize; i++) {
    const lineY = roundedY + i * cellHeight;
    if (isFinite(lineY)) {
      path += `M ${roundedX} ${Math.round(lineY * 100) / 100} L ${roundedX + roundedWidth} ${Math.round(lineY * 100) / 100} `;
    }
  }

  return path;
};

/**
 * 拖动点改变裁剪框大小的封装方法
 * @param handleType - 拖动点类型
 * @param startRect - 原始裁剪框位置和尺寸
 * @param deltaX - X轴方向移动距离
 * @param deltaY - Y轴方向移动距离
 * @param ratio - 比例参数，如[1,1]表示1:1，[4,3]表示4:3，null表示自由调整
 * @param imageSize - 图片显示尺寸
 * @param imagePosition - 图片在画布中的位置
 * @param toolKey - 工具类型键值
 * @returns 新的裁剪框位置和尺寸
 */
export const resizeCropRectByHandle = (
  handleType: string,
  startRect: CropRect,
  deltaX: number,
  deltaY: number,
  ratio: [number, number] | null,
  imageSize: ImageSize,
  imagePosition: ImagePosition,
  toolKey?: string
): CropRect => {
  "worklet";
  if (toolKey === "original") return startRect;

  let newRect = { ...startRect };
  const minSize = 50;

  if (ratio) {
    // 保持比例缩放，固定对角位置，到达边缘停止缩放
    const [wR, hR] = ratio;
    const targetRatio = hR / wR;

    switch (handleType) {
      case "top-left": {
        // 固定右下角，调整左上角
        const maxWidth = startRect.x + startRect.width - imagePosition.x;
        const maxHeight = startRect.y + startRect.height - imagePosition.y;

        let newWidth = Math.max(minSize, startRect.width - deltaX);
        let newHeight = newWidth * targetRatio;

        // 检查是否超出边界，如果超出则停止缩放
        if (newWidth > maxWidth || newHeight > maxHeight) {
          const widthScale = maxWidth / startRect.width;
          const heightScale = maxHeight / (startRect.width * targetRatio);
          const scale = Math.min(widthScale, heightScale);
          newWidth = startRect.width * scale;
          newHeight = newWidth * targetRatio;
        }

        newRect.width = newWidth;
        newRect.height = newHeight;
        newRect.x = startRect.x + startRect.width - newRect.width;
        newRect.y = startRect.y + startRect.height - newRect.height;
        break;
      }
      case "top-right": {
        // 固定左下角，调整右上角
        const maxWidth = imageSize.width - (startRect.x - imagePosition.x);
        const maxHeight = startRect.y + startRect.height - imagePosition.y;

        let newWidth = Math.max(minSize, startRect.width + deltaX);
        let newHeight = newWidth * targetRatio;

        // 检查是否超出边界，如果超出则停止缩放
        if (newWidth > maxWidth || newHeight > maxHeight) {
          const widthScale = maxWidth / startRect.width;
          const heightScale = maxHeight / (startRect.width * targetRatio);
          const scale = Math.min(widthScale, heightScale);
          newWidth = startRect.width * scale;
          newHeight = newWidth * targetRatio;
        }

        newRect.width = newWidth;
        newRect.height = newHeight;
        newRect.y = startRect.y + startRect.height - newRect.height;
        break;
      }
      case "bottom-left": {
        // 固定右上角，调整左下角
        const maxWidth = startRect.x + startRect.width - imagePosition.x;
        const maxHeight = imageSize.height - (startRect.y - imagePosition.y);

        let newWidth = Math.max(minSize, startRect.width - deltaX);
        let newHeight = newWidth * targetRatio;

        // 检查是否超出边界，如果超出则停止缩放
        if (newWidth > maxWidth || newHeight > maxHeight) {
          const widthScale = maxWidth / startRect.width;
          const heightScale = maxHeight / (startRect.width * targetRatio);
          const scale = Math.min(widthScale, heightScale);
          newWidth = startRect.width * scale;
          newHeight = newWidth * targetRatio;
        }

        newRect.width = newWidth;
        newRect.height = newHeight;
        newRect.x = startRect.x + startRect.width - newRect.width;
        break;
      }
      case "bottom-right": {
        // 固定左上角，调整右下角
        const maxWidth = imageSize.width - (startRect.x - imagePosition.x);
        const maxHeight = imageSize.height - (startRect.y - imagePosition.y);

        let newWidth = Math.max(minSize, startRect.width + deltaX);
        let newHeight = newWidth * targetRatio;

        // 检查是否超出边界，如果超出则停止缩放
        if (newWidth > maxWidth || newHeight > maxHeight) {
          const widthScale = maxWidth / startRect.width;
          const heightScale = maxHeight / (startRect.width * targetRatio);
          const scale = Math.min(widthScale, heightScale);
          newWidth = startRect.width * scale;
          newHeight = newWidth * targetRatio;
        }

        newRect.width = newWidth;
        newRect.height = newHeight;
        break;
      }
    }
  } else {
    // 自由调整 - 固定对角点
    switch (handleType) {
      case "top-left":
        // 固定右下角，调整左上角
        const maxWidthTL = startRect.x + startRect.width - imagePosition.x;
        const maxHeightTL = startRect.y + startRect.height - imagePosition.y;

        let newWidthTL = Math.max(minSize, startRect.width - deltaX);
        let newHeightTL = Math.max(minSize, startRect.height - deltaY);

        // 限制在图片范围内
        newWidthTL = Math.min(newWidthTL, maxWidthTL);
        newHeightTL = Math.min(newHeightTL, maxHeightTL);

        newRect.width = newWidthTL;
        newRect.height = newHeightTL;
        newRect.x = startRect.x + startRect.width - newRect.width;
        newRect.y = startRect.y + startRect.height - newRect.height;
        break;
      case "top-right":
        // 固定左下角，调整右上角
        const maxWidthTR = imageSize.width - (startRect.x - imagePosition.x);
        const maxHeightTR = startRect.y + startRect.height - imagePosition.y;

        let newWidthTR = Math.max(minSize, startRect.width + deltaX);
        let newHeightTR = Math.max(minSize, startRect.height - deltaY);

        // 限制在图片范围内
        newWidthTR = Math.min(newWidthTR, maxWidthTR);
        newHeightTR = Math.min(newHeightTR, maxHeightTR);

        newRect.width = newWidthTR;
        newRect.height = newHeightTR;
        newRect.y = startRect.y + startRect.height - newRect.height;
        break;
      case "bottom-left":
        // 固定右上角，调整左下角
        const maxWidthBL = startRect.x + startRect.width - imagePosition.x;
        const maxHeightBL = imageSize.height - (startRect.y - imagePosition.y);

        let newWidthBL = Math.max(minSize, startRect.width - deltaX);
        let newHeightBL = Math.max(minSize, startRect.height + deltaY);

        // 限制在图片范围内
        newWidthBL = Math.min(newWidthBL, maxWidthBL);
        newHeightBL = Math.min(newHeightBL, maxHeightBL);

        newRect.width = newWidthBL;
        newRect.height = newHeightBL;
        newRect.x = startRect.x + startRect.width - newRect.width;
        break;
      case "bottom-right":
        // 固定左上角，调整右下角
        const maxWidthBR = imageSize.width - (startRect.x - imagePosition.x);
        const maxHeightBR = imageSize.height - (startRect.y - imagePosition.y);

        let newWidthBR = Math.max(minSize, startRect.width + deltaX);
        let newHeightBR = Math.max(minSize, startRect.height + deltaY);

        // 限制在图片范围内
        newWidthBR = Math.min(newWidthBR, maxWidthBR);
        newHeightBR = Math.min(newHeightBR, maxHeightBR);

        newRect.width = newWidthBR;
        newRect.height = newHeightBR;
        break;
      case "top":
        // 固定底部，调整顶部
        const maxHeightTop = startRect.y + startRect.height - imagePosition.y;
        let newHeightTop = Math.max(minSize, startRect.height - deltaY);
        newHeightTop = Math.min(newHeightTop, maxHeightTop);
        newRect.height = newHeightTop;
        newRect.y = startRect.y + startRect.height - newRect.height;
        break;
      case "bottom":
        // 固定顶部，调整底部
        const maxHeightBottom =
          imageSize.height - (startRect.y - imagePosition.y);
        let newHeightBottom = Math.max(minSize, startRect.height + deltaY);
        newHeightBottom = Math.min(newHeightBottom, maxHeightBottom);
        newRect.height = newHeightBottom;
        break;
      case "left":
        // 固定右侧，调整左侧
        const maxWidthLeft = startRect.x + startRect.width - imagePosition.x;
        let newWidthLeft = Math.max(minSize, startRect.width - deltaX);
        newWidthLeft = Math.min(newWidthLeft, maxWidthLeft);
        newRect.width = newWidthLeft;
        newRect.x = startRect.x + startRect.width - newRect.width;
        break;
      case "right":
        // 固定左侧，调整右侧
        const maxWidthRight = imageSize.width - (startRect.x - imagePosition.x);
        let newWidthRight = Math.max(minSize, startRect.width + deltaX);
        newWidthRight = Math.min(newWidthRight, maxWidthRight);
        newRect.width = newWidthRight;
        break;
    }
  }

  // 限制在图片范围内
  newRect.x = Math.max(
    imagePosition.x,
    Math.min(newRect.x, imagePosition.x + imageSize.width - newRect.width)
  );
  newRect.y = Math.max(
    imagePosition.y,
    Math.min(newRect.y, imagePosition.y + imageSize.height - newRect.height)
  );
  newRect.width = Math.min(
    newRect.width,
    imageSize.width - (newRect.x - imagePosition.x)
  );
  newRect.height = Math.min(
    newRect.height,
    imageSize.height - (newRect.y - imagePosition.y)
  );

  return newRect;
};

/**
 * 获取手柄的边界矩形（用于精确检测）
 * @param handle - 拖动点信息
 * @returns 边界矩形
 */
export const getHandleBounds = (
  handle: DragHandle
): { x: number; y: number; width: number; height: number } => {
  'worklet';
  const cornerSize = 20;
  const edgeWidth = 30;
  const edgeHeight = 5;
  const padding = 30; // 增加点击容错范围，提高操作灵敏度

  switch (handle.type) {
    case "top-left":
      return {
        x: handle.x - padding,
        y: handle.y - padding,
        width: cornerSize + padding * 2,
        height: cornerSize + padding * 2,
      };
    case "top-right":
      return {
        x: handle.x - cornerSize - padding,
        y: handle.y - padding,
        width: cornerSize + padding * 2,
        height: cornerSize + padding * 2,
      };
    case "bottom-left":
      return {
        x: handle.x - padding,
        y: handle.y - cornerSize - padding,
        width: cornerSize + padding * 2,
        height: cornerSize + padding * 2,
      };
    case "bottom-right":
      return {
        x: handle.x - cornerSize - padding,
        y: handle.y - cornerSize - padding,
        width: cornerSize + padding * 2,
        height: cornerSize + padding * 2,
      };
    case "top":
      return {
        x: handle.x - edgeWidth / 2 - padding,
        y: handle.y - padding,
        width: edgeWidth + padding * 2,
        height: edgeHeight + padding * 2,
      };
    case "bottom":
      return {
        x: handle.x - edgeWidth / 2 - padding,
        y: handle.y - edgeHeight - padding,
        width: edgeWidth + padding * 2,
        height: edgeHeight + padding * 2,
      };
    case "left":
      return {
        x: handle.x - padding,
        y: handle.y - edgeWidth / 2 - padding,
        width: edgeHeight + padding * 2,
        height: edgeWidth + padding * 2,
      };
    case "right":
      return {
        x: handle.x - edgeHeight - padding,
        y: handle.y - edgeWidth / 2 - padding,
        width: edgeHeight + padding * 2,
        height: edgeWidth + padding * 2,
      };
    default:
      return {
        x: handle.x - 6 - padding,
        y: handle.y - 6 - padding,
        width: 12 + padding * 2,
        height: 12 + padding * 2,
      };
  }
};

/**
 * 检测点击的拖动点
 * @param touchX - 触摸X坐标
 * @param touchY - 触摸Y坐标
 * @param handles - 拖动点数组
 * @returns 点击的拖动点或null
 */
export const detectClickedHandle = (
  touchX: number,
  touchY: number,
  handles: DragHandle[]
): DragHandle | null => {
  "worklet";
  for (const handle of handles) {
    const bounds = getHandleBounds(handle);
    if (
      touchX >= bounds.x &&
      touchX <= bounds.x + bounds.width &&
      touchY >= bounds.y &&
      touchY <= bounds.y + bounds.height
    ) {
      return handle;
    }
  }
  return null;
};

/**
 * 检测点击是否在裁剪框内部
 * @param x - 点击X坐标
 * @param y - 点击Y坐标
 * @param cropRect - 裁剪框位置和尺寸
 * @returns 是否在裁剪框内
 */
export const isPointInCropRect = (
  x: number,
  y: number,
  cropRect: CropRect
): boolean => {
  return (
    x >= cropRect.x &&
    x <= cropRect.x + cropRect.width &&
    y >= cropRect.y &&
    y <= cropRect.y + cropRect.height
  );
};

/**
 * 计算图片显示尺寸（确保不超出画布边界）
 * @param skiaImage - Skia图片对象
 * @param containerSize - 容器尺寸
 * @param marginHorizontal - 水平边距
 * @returns 图片显示尺寸
 */
export const getImageDisplaySize = (
  skiaImage: any,
  containerSize: { width: number; height: number },
  marginHorizontal: number = 0
): ImageSize => {
  if (!skiaImage || containerSize.width === 0 || containerSize.height === 0) {
    return { width: 0, height: 0 };
  }

  const originalWidth = skiaImage.width();
  const originalHeight = skiaImage.height();
  const aspectRatio = originalHeight / originalWidth;

  // 考虑左右边距后的可用宽度
  const availableWidth = containerSize.width - marginHorizontal * 2;
  let displayWidth = availableWidth;
  let displayHeight = displayWidth * aspectRatio;

  // 如果高度超出容器，按高度缩放
  if (displayHeight > containerSize.height) {
    displayHeight = containerSize.height;
    displayWidth = displayHeight / aspectRatio;
  }

  return {
    width: displayWidth,
    height: displayHeight,
  };
};

/**
 * 计算居中位置（考虑边距）
 * @param imageSize - 图片显示尺寸
 * @param containerSize - 容器尺寸
 * @param marginHorizontal - 水平边距
 * @returns 图片在画布中的位置
 */
export const getCenteredPosition = (
  imageSize: ImageSize,
  containerSize: { width: number; height: number }
): ImagePosition => {
  if (imageSize.width === 0 || imageSize.height === 0) {
    return { x: 0, y: 0 };
  }

  return {
    x: (containerSize.width - imageSize.width) / 2,
    y: (containerSize.height - imageSize.height) / 2,
  };
};
